let currentPage = 1; // 当前页码
let totalPages = 1; // 总页数
let isLoading = false; // 加载状态标记

let hasMorePosts = true;
let currentPostId = null;
// 监听滚动事件
window.addEventListener('scroll', checkScroll);

function checkScroll() {
    // 如果正在加载或没有更多帖子，则不执行任何操作
    if (isLoading || !hasMorePosts) return;

    // 计算是否接近页面底部
    const scrollHeight = document.documentElement.scrollHeight;
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;

    if (scrollTop + clientHeight >= scrollHeight - 300) {
        loadMorePosts();
        console.log("监测成功一次")
    }
}


function loadMorePosts() {
    isLoading = true;

    // 显示加载指示器
    const loadingIndicator = document.createElement('div');
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.innerHTML = '<i class="iconfont">&#xe60f;</i> 加载中...';
    document.querySelector('.content-grid').appendChild(loadingIndicator);

    $.ajax({
        url: `/mainPageVedio/more?pageNum=${currentPage + 1}`,
        type: 'GET',
        success: function(result) {
            console.log('加载结果:', result);

            // 处理无更多数据的情况
            if (!result.postsPageInfo || !result.postsPageInfo.list || result.postsPageInfo.list.length === 0) {
                hasMorePosts = false;
                loadingIndicator.innerHTML = '没有更多内容了';
                setTimeout(() => loadingIndicator.remove(), 2000);
                return;
            }

            // 提取分页数据和用户列表
            const posts = result.postsPageInfo.list;
            const users = result.postsUsers || [];

            // 生成模板字符串
            const html = posts.map((post, index) => {
                const user = users[index] || { username: '未知用户' }; // 确保用户对象不为空
                const isLiked = post.isLiked ? 'isLiked' : ''; // 点赞状态

                return `
                <div class="content-grid">
                    <div class="content-item">
                        <video controls>
                            <source src="${post.filePath}" type="video/mp4">
                            您的浏览器不支持视频播放。
                        </video>
                        <a  th:href="@{/videos/select/id?id={id}(id=${video.videoId})}" style="color: black">
                        <p class="title">${post.title}</p>
                        <div class="author">
                            <span>${user.username}</span>
                        </div>
                        </a>
                        <div class="likes" >  <button  class="top-story-content-footer-button top-story-content-footer-button-like"  th:value="${video.videoId}"   th:data-is-liked="${video.isLike }"><i class="iconfont like" >&#xe610;</i>喜欢</button></div>
                        
                    </div>
                </div>
                `;
            }).join('');

            // 插入到页面指定位置（示例：top-story-content-recommend 容器）
            const container = document.querySelector('.content-grid');
            container.insertAdjacentHTML('beforeend', html);

            // 更新页码和状态
            currentPage++;
            loadingIndicator.remove();
            isLoading = false;
            let top_story_content_footer_button_likes=document.getElementsByClassName('top-story-content-footer-button-like')
            let likes=document.getElementsByClassName('like')
            for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
                top_story_content_footer_button_likes[i].addEventListener('click', function () {
                    console.log("被点赞")

                    let like_value=top_story_content_footer_button_likes[i].value
                    const postIdNum = Number(like_value);
                    console.log(postIdNum)
                    console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
                    if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)') {

                        $.ajax({
                            url: `/videos/like?videoId=${like_value}`,

                            type: 'POST',
                            data: {videoId: postIdNum},
                            success: function (result) {
                                showCustomAlert('点赞成功', 3000)
                                top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                                likes[i].style.color= 'rgba(255,0,0)'
                                console.log('发送点赞请求到:', this.url);
                            },
                            error: function (error) {
                                showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                                console.log(error);
                                console.log('发送点赞请求到:', this.url);
                            }

                        })

                    }else {
                        console.log(1111111)
                        $.ajax({
                            url: `/videos/cancelLike?videoId=${like_value}`,

                            type: 'POST',
                            data: {videoId: postIdNum},
                            success: function (result) {
                                showCustomAlert('取消点赞', 3000)
                                top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                                likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                                console.log('发送点赞请求到:', this.url);
                            },
                            error: function (error) {
                                showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                                console.log(error);
                                console.log('发送点赞请求到:', this.url);
                            }

                        })
                    }
                    1
                })
            }

        },
        error: function(error) {
            console.error('加载失败:', error);
            loadingIndicator.innerHTML = '加载失败，请重试';
            setTimeout(() => loadingIndicator.remove(), 2000);
            isLoading = false;
        }
    });
}
let top_story_content_footer_button_likes=document.getElementsByClassName('top-story-content-footer-button-like')
let likes=document.getElementsByClassName('like')
for (let i = 0; i < top_story_content_footer_button_likes.length; i++) {
    top_story_content_footer_button_likes[i].addEventListener('click', function () {


        let like_value=top_story_content_footer_button_likes[i].value
        const postIdNum = Number(like_value);
        console.log(postIdNum)
        console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
        if (window.getComputedStyle(top_story_content_footer_button_likes[i]).color === 'rgba(169, 178, 185, 0.937)') {

            $.ajax({
                url: `/videos/like?videoId=${like_value}`,

                type: 'POST',
                data: {videoId: postIdNum},
                success: function (result) {
                    showCustomAlert('点赞成功', 3000)
                    console.log(top_story_content_footer_button_likes[i].dataset.isLiked)
                    top_story_content_footer_button_likes[i].style.color= 'rgba(255,0,0,1)'
                    likes[i].style.color= 'rgba(255,0,0)'
                    // top_story_content_footer_button_likes[i].dataset.isLiked++;
                    console.log(top_story_content_footer_button_likes[i].dataset.isLiked)
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })

        }else {
            console.log(1111111)
            $.ajax({
                url: `/videos/cancelLike?videoId=${like_value}`,

                type: 'POST',
                data: {videoId: postIdNum},
                success: function (result) {
                    showCustomAlert('取消点赞', 3000)
                    // top_story_content_footer_button_likes[i].dataset.isLiked--;
                    top_story_content_footer_button_likes[i].style.color = 'rgba(169, 178, 185, 0.937)'
                    likes[i].style.color= 'rgba(169, 178, 185, 0.937)'
                    console.log('发送点赞请求到:', this.url);
                },
                error: function (error) {
                    showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                    console.log(error);
                    console.log('发送点赞请求到:', this.url);
                }

            })
        }

    })
}